package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lutzyt.delivery.bean.User;
import com.lutzyt.delivery.bean.UserRole;
import com.lutzyt.delivery.mapper.UserRoleDAO;
import com.lutzyt.delivery.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDAO, UserRole> implements UserRoleService {

  private static final String USER_ID = "user_id";
  private static final String ROLE_ID = "role_id";
  private UserRoleDAO userRoleDAO;

  @Transactional(readOnly = true)
  @Override
  public UserRole findById(Integer id) {
    final List<UserRole> list = this.query().eq(USER_ID, id).list();
    final List<Integer> roleIds = list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
    UserRole userRole = new UserRole();
    userRole.setRoleIds(roleIds);
    userRole.setUserId(id);
    return userRole;
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<UserRole> findByPage(int pageNum, int pageSize) {
    return userRoleDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(UserRole userRole) {
    final List<Integer> roleIdList = userRole.getRoleIds();
    // 删除不存在于roleIds中用户角色映射
    this.update().eq(USER_ID, userRole.getUserId()).notIn(!roleIdList.isEmpty(), ROLE_ID, roleIdList).remove();
    final List<Integer> roleIds = this.findById(userRole.getUserId()).getRoleIds();
    List<UserRole> userRoles = new ArrayList<>();
    roleIdList.stream().filter(roleId->!roleIds.contains(roleId)).forEach(roleId->{
      UserRole bean = new UserRole();
      bean.setUserId(userRole.getUserId());
      bean.setRoleId(roleId);
      userRoles.add(bean);
    });
    this.saveBatch(userRoles);
  }

  @Override
  public void update(UserRole userRole) {
    userRoleDAO.updateById(userRole);
  }

  @Override
  public void deleteById(Integer id) {
    userRoleDAO.deleteById(id);
  }


  @Autowired
  public void setUserRoleDAO(UserRoleDAO userRoleDAO) {
    this.userRoleDAO = userRoleDAO;
  }
}